/*
 *
 * Copyright (c) 2021
 * User:Dybala
 * File:RegisterService.java
 * Date:2021/11/13 19:16:13
 */

package com.service;

import com.dao.UserDao;
import com.pojo.Message;
import com.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.Map;

/**
 * 用于校验注册
 */
@Service
public class RegisterService {

    @Autowired
    UserDao dao;
    public Message register(@RequestBody Map<String, String> map){
        String email = map.get("email");
        String username = map.get("username");
        String password = map.get("password");
        String phone=map.get("phone");
        User user=new User();
        user.setEmail(email);
        user.setUsername(username);
        user.setPassword(password);
        user.setPhone(phone);
        Message msg=new Message();
        if(password==null||password.length()<6){
            msg.setFlag(400);
            msg.setMsg("密码太短");
            return msg;
        }
        if(!email.contains("@")){
            msg.setFlag(400);
            msg.setMsg("邮件格式不正确");
            return msg;
        }
        //先校验是否有这个用户
        boolean flag=verifyIsExist(user.getEmail());
        if(!flag){
            msg.setFlag(400);
            msg.setMsg("该邮箱已被注册，请换个邮箱试试");
        }else{
            //表示暂时激活
            user.setStatus("active");
            int num = dao.addUser(user);
            msg.setFlag(200);
            msg.setMsg("注册成功 "+num);
        }
        return msg;
    }

    /**
     * 校验是否已经存在这个用户
     * @param email
     * @return
     */
    private boolean verifyIsExist(String email){
        User user = dao.queryByEmail(email);
        if(user==null)
        return true;
        else return false;
    }

}
